% Display area activity as a movie given the sdat spike history from the C simulation.
%  displayWts({'areaname1' 'areaname2' ...}, sdat, start_time, end_time, smooth_msec, bin_msec, write_avi_movie)
% 
%  if smooth_msec ~=1, then it smooths with time constant = smooth_msec.
%  bin_msec bins 'bin_msec' milliseconds together
%
% Assumes that groups.dat has the neural area data.
% If area_cell_array is empty, then display them all; in this case, leave
% subplot_dim empty as well, or make the subplot grid big enough.
% 
% Read 1 second at a time for real-time display as sim runs.
% 
% For the demo:
% 1. From the terminal window, enter:
%   rm spikes*.dat
%   ./run 8
% 2. In the matlab command window:
%   displayMovieRT({'S1p23','S1b23','S1TCs'},0,19999,5,5);
function displayMovie(area_cell_array, start_time, end_time, smooth_msec, bin_msec, subplot_dim, write_avi_movie)

global a


read_groups; % Assumes groups.dat has the neural area data


if nargin < 4
	smooth_msec = 1
end
if nargin < 5
	bin_msec = 1
end
if nargin < 7
	write_avi_movie = false
end


if bin_msec > 1000
    disp('bin_msec cannot be greater than 1000 msec.')
    return;
end

for i=1:length(areas)
    group_name{i} = strcat(areas{i},celltype{i});
end

% If empty, display them all!
if( length(area_cell_array)==0)
    area_cell_array = group_name;
end

if nargin < 6
	subplot_dim = [ceil(sqrt(length(area_cell_array))) ceil(sqrt(length(area_cell_array)))]; 
end



for i = 1:length(area_cell_array)
	index(i) = find(strcmp( area_cell_array{i},group_name) );
    if isempty(index(i))
        disp([area_cell_array{i} ' is not in groups.dat.']);
        return;
    end
end



start_time = start_time + 1;
end_time = end_time + 1;


save_seconds = 1;

clear a;

for i = 1:length(area_cell_array)

	first(i) = neuron_id(index(i),1);
	last(i) = neuron_id(index(i),2);
	first(i) = first(i) + 1;
	last(i) = last(i) + 1;
	rows(i) = la(index(i));
	cols(i) = lb(index(i));
	a(i).a=zeros(rows(i),cols(i));
end

num_neurons = max(last);


%       set(gca,'xlim',[-80 80],'ylim',[-80 80],...
%       	   'NextPlot','replace','Visible','off')



fig=figure;
set(fig,'DoubleBuffer','on');

if write_avi_movie 
	mov = avifile('network.avi')
end

factor = 1000/bin_msec;
alpha = exp(-1/(smooth_msec/bin_msec));
current_spikes = [];

% Read the first spike file.
filelabeltime = floor((start_time+1000)/1000)*1000;
filename = ['spikes' num2str(filelabeltime) '.dat'];
previous_spikes = current_spikes;
while ~exist( filename, 'file' )
    pause(.25);
end
current_spikes=load( filename );
sp=[previous_spikes;current_spikes];
time_read = filelabeltime;

S=sparse(sp(:,2)+1, sp(:,1)+1, ones(size(sp,1),1), max(num_neurons,max(sp(:,2))+1), max(max(sp(:,1))+1,end_time));


for i=start_time:bin_msec:end_time 

    if i+bin_msec >= time_read
        % Better read the next file.
        filelabeltime = floor((time_read+1000)/1000)*1000;
        filename = ['spikes' num2str(filelabeltime) '.dat'];
        previous_spikes = current_spikes;
        while ~exist( filename, 'file' )
            pause(.25);
        end
        current_spikes=load(filename);
        sp=[previous_spikes;current_spikes];
        time_read = filelabeltime;

        S=sparse(sp(:,2)+1, sp(:,1)+1, ones(size(sp,1),1), max(num_neurons,max(sp(:,2))+1), max(max(sp(:,1))+1,end_time));

    end    
    
   for area_i = 1:length(area_cell_array)
	subplot( subplot_dim(1), subplot_dim(2), area_i);
    %set(gca,'nextplot','replacechildren');
	if smooth_msec > 1
		a(area_i).a=alpha*a(area_i).a + (1-alpha)*factor*reshape( sum( S( first(area_i):last(area_i), i:(i+bin_msec-1)) ,2) , rows(area_i), cols(area_i) )';
		%a(area).a=(smooth_msec-1)/smooth_msec*a(area).a + reshape( S( first(area):last(area), i) , rows(area), cols(area) );

		imagesc( a(area_i).a ,[0 10]); colormap(gray);
		%imagesc( a(area_i).a); 
	else
		%imagesc( factor*full(reshape( sum( S( first(area_i):last(area_i), i:(i+bin_msec-1)) ,2) , rows(area_i), cols(area_i) ))); colormap(gray)
		imagesc( factor*full(reshape( sum( S( first(area_i):last(area_i), i:(i+bin_msec-1)) ,2) , rows(area_i), cols(area_i) )') ,[0 10]);  colormap(gray);
	end
    axis off
	
	title( area_cell_array{area_i} );


   end

   axis on
   xlabel(num2str(i));
   drawnow;
   %pause(.5); 

   if write_avi_movie 
	F = getframe(gcf);
   	mov = addframe(mov,F);
   end
end

if write_avi_movie
	mov = close(mov);
end